# MonkeyRunner Python script used to run an automated 
# test of the packageHandler implemented in sw6.admin.
# 
# To use this script, please make sure that:
# - you start it from the monkeyStarter.bat
# - you have monkeyrunner in your currentPath (\android-sdk\tools)
# - you have installed the sw6.packageHandler project on the phone
#   (the project can be imported from google code where it is
#	a part of the sw6.tests project)

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# used to enable sleep
import time

# used to enable currentPath operations
import os

# used to enable regex
import re

# used for improved output
def printDelimiter() :
	print '-------------------------'

# List of apk files
apkPackageNameList = []

# List of apk files with currentPath
apkFilePathList = []

# Current path
currentPath = os.path.dirname(__file__)

# Change dir to the apps folder where the test apk files are located
currentPath = os.path.join(currentPath, 'apps')

# Used to setup test environment
sw6AdminApk = currentPath + '\\' + 'sw6.admin.apk'
sw6PackageHandlerTestApk = currentPath + '\\' + 'sw6.packageHandler.apk'
sw6AdminPkg = 'sw6.admin'
sw6PackageHandlerTestPkg = 'sw6.packageHandler'

# List apps dir
appsDirList = os.listdir(currentPath)

# Loop through the dir and store the filename and filename with path
# of the test apps located in the apps folder
for fname in appsDirList:

	# Do this check to ignore files of no interest
    if fname.startswith('sw6',0,3) == 1:
	
		# Get package name of the test app
		matchPackage = re.match( r'sw6\.app[0-9]{1}', fname, re.M|re.I)
		
		# If a valid package name was found
		if matchPackage:
			
			printDelimiter()
			
			# Get the first match (there will only be one)
			matchedPackageName = matchPackage.group()
			
			# Append the current packagename to the list of package names
			apkPackageNameList.append(matchedPackageName)
			print 'Found .apk file with package name: ' + apkPackageNameList[len(apkPackageNameList)-1]
			
			# Define the path of the current file
			fPath = currentPath + '\\' + fname
			
			# Append the current filepath of the found apk to the list of paths to valid test apk files
			apkFilePathList.append(fPath)
			print 'Found .apk file with file path: ' + apkFilePathList[len(apkFilePathList)-1]

# Function to remove duplicated entries in a list
def removeDuplicates(seq): 
	# Order is preserved
	checked = []
	for e in seq:
		if e not in checked:
			checked.append(e)
	return checked

# Remove duplicates
apkPackageNameList = removeDuplicates(apkPackageNameList)
apkFilePathList = removeDuplicates(apkFilePathList)

# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()

# Remove sw6.admin and sw6.packageHandler
printDelimiter()
print 'Setting up test environment...'

print 'Removing sw6.admin...'
device.removePackage(sw6AdminPkg);
print 'Removed.'
print 'Removing sw6.packageHandler...'
device.removePackage(sw6PackageHandlerTestPkg);
print 'Removed.'

print 'Installing sw6.admin...'
device.installPackage(sw6AdminApk);
print 'Installed.'
print 'Installing sw6.packageHandler...'
device.installPackage(sw6PackageHandlerTestApk);
print 'Installed.'

print 'Environment setup done.'

for i in range(1,3):

	printDelimiter()
	if(i == 1) :	
		print 'TESTING MAJOR RUN #' + repr(i) + ' WHERE SW6.ADMIN DB DOES NOT EXISTS FROM START...'
	else :
		print 'TESTING MAJOR RUN #' + repr(i) + ' WHERE SW6.ADMIN DB DOES EXISTS FROM START...'

	# Remove packages
	printDelimiter()
	for item in apkPackageNameList:
		print 'Removing...'
		device.removePackage(item)
		print 'Removed: ', item
		
	# Sets a variable with the test-package's internal name
	package = 'sw6.packageHandler'

	# Sets a variable with the name of an Activity in the package
	activity = package + '.PackageHandlerTest'

	# Sets the name of the component to start by the monkey
	runComponent = package + '/' + activity

	# Runs the component
	printDelimiter()
	print 'Starting sw6.packageHandler PackageHandlerTest Activity...'
	device.startActivity(component=runComponent)	
		
	# Run the tests, initial version is 1	
	version = 1

	while(1) :
		hasRun = 0
		
		# For each apk file with the current version:
		# - ensure they are installed (and that
		#   older versions are upgraded)
		printDelimiter()
		for apkFilePath in apkFilePathList :
			str = repr(version)
			apkFilePathMatch = re.match( r'.*sw6\.app[0-9]{1}v[' + str + ']{1}\.apk', apkFilePath, re.M|re.I)

			if apkFilePathMatch:
				hasRun = 1
				print 'Installing...'
				device.installPackage(apkFilePathMatch.group())
				print 'Installed: ', apkFilePathMatch.group()
				
		# If new packages have been installed, make 
		# the monkey run the tests.
		if(hasRun) :
			printDelimiter()
			print 'Running test...'
			print 'The monkey is working on the screen...'
			device.press('KEYCODE_DPAD_RIGHT ','DOWN_AND_UP')
			time.sleep(1)
			device.press('KEYCODE_DPAD_RIGHT ','DOWN_AND_UP')
			time.sleep(1)
			device.press('KEYCODE_DPAD_CENTER ','DOWN_AND_UP')
			time.sleep(10)
			device.press('KEYCODE_DPAD_LEFT ','DOWN_AND_UP')
			version = version + 1
		else :
			break
		
print 'Donez - Controlled monkeytest has finished.'